/**
 * 前端主应用逻辑文件
 * 
 * 主要功能：
 * 1. 页面初始化和事件绑定
 * 2. 用户认证状态检查
 * 3. 账本切换和数据加载
 * 4. 记录的增删改查操作
 * 5. 统计数据和图表展示
 * 6. UI交互和用户体验优化
 * 
 * 文件结构：
 * - 全局变量定义
 * - 页面加载初始化
 * - 核心业务函数
 * - 工具函数
 * - 事件处理函数
 * 
 * @author 个人预算管理系统开发团队
 * @date 2025-10-26
 */

// ==================== 全局变量定义 ====================

/**
 * 当前选中的账本ID
 * @type {number|null}
 * @description 用户当前查看的账本ID，null表示未选择账本
 */
let currentBookId = null;

/**
 * 所有账本列表
 * @type {array}
 * @description 缓存用户的所有账本，避免重复请求
 */
let allBooks = [];

/**
 * 当前选中的图标
 * @type {string}
 * @description 创建账本时选择的emoji图标
 */
let selectedIcon = '💰';

/**
 * 当前选中的颜色
 * @type {string}
 * @description 创建账本时选择的主题颜色（HEX格式）
 */
let selectedColor = '#4285f4';

// ==================== 分类映射常量 ====================

/**
 * 收入分类映射表
 * 
 * @const {object} incomeCategories
 * @property {string} salary - 工资
 * @property {string} bonus - 奖金
 * @property {string} investment - 投资
 * @property {string} gift - 礼金
 * @property {string} other - 其他
 * 
 * @description 将英文分类键映射为中文显示名称
 */
const incomeCategories = {
  salary: '工资',
  bonus: '奖金',
  investment: '投资',
  gift: '礼金',
  other: '其他'
};

/**
 * 支出分类映射表
 * 
 * @const {object} expenseCategories
 * @property {string} food - 餐饮
 * @property {string} transport - 交通
 * @property {string} shopping - 购物
 * @property {string} entertainment - 娱乐
 * @property {string} healthcare - 医疗
 * @property {string} education - 教育
 * @property {string} housing - 住房
 * @property {string} utilities - 水电
 * @property {string} other - 其他
 * 
 * @description 将英文分类键映射为中文显示名称
 */
const expenseCategories = {
  food: '餐饮',
  transport: '交通',
  shopping: '购物',
  entertainment: '娱乐',
  healthcare: '医疗',
  education: '教育',
  housing: '住房',
  utilities: '水电',
  other: '其他'
};

// ==================== UI配置常量 ====================

/**
 * 可选的账本图标列表
 * @const {array} icons
 * @description 创建账本时可选择的emoji图标
 */
const icons = ['💰', '🏠', '✈️', '💍', '📊', '🎉', '🎓', '🚗', '🏥', '🍔'];

/**
 * 可选的主题颜色列表
 * @const {array} colors
 * @description 创建账本时可选择的主题颜色（HEX格式）
 */
const colors = ['#4285f4', '#34a853', '#fbbc04', '#ea4335', '#9c27b0', '#00bcd4', '#ff5722', '#795548'];

// ==================== 页面加载初始化 ====================

/**
 * DOM内容加载完成事件监听
 * 
 * @event DOMContentLoaded
 * @description 页面DOM加载完成后执行初始化流程
 * 
 * 初始化流程：
 * 1. checkAuth() - 检查用户认证状态
 * 2. initializeUI() - 初始化UI界面
 * 3. loadBooks() - 加载账本列表
 * 4. setupEventListeners() - 绑定事件监听器
 * 5. loadTheme() - 加载主题设置
 * 6. loadTags() - 加载标签列表
 * 7. loadBooksCompare() - 加载账本对比数据
 * 
 * 设计思路：
 * 1. 先检查认证，未登录直接跳转登录页
 * 2. 认证通过后再初始化，避免无用的API请求
 * 3. 初始化顺序有依赖关系（如先加载账本，再加载记录）
 */
document.addEventListener('DOMContentLoaded', () => {
  // 1. 先检查认证状态
  // 如果未登录，checkAuth()会跳转到登录页并返回false
  if (!checkAuth()) {
    return; // 认证失败，停止初始化
  }
  
  // 2. 认证通过，继续初始化
  initializeUI();          // 初始化UI组件
  loadBooks();             // 加载账本列表
  setupEventListeners();   // 绑定事件监听器
  loadTheme();             // 加载主题设置
  loadTags();              // 加载标签列表
  loadBooksCompare();      // 加载账本对比
  
  // 游戏化功能在 gamification-ui.js 中单独处理
  // 这样可以实现功能的模块化和解耦
});

// ==================== 认证检查函数 ====================

/**
 * 检查用户认证状态
 * 
 * @function checkAuth
 * @returns {boolean} 认证是否通过（true: 已登录，false: 未登录）
 * 
 * @description 检查localStorage中是否有token和username
 * 
 * 工作流程：
 * 1. 从localStorage读取token和username
 * 2. 如果任一缺失，跳转到登录页
 * 3. 如果都存在，显示用户名并返回true
 * 
 * 设计思路：
 * 1. 双重检查：token和username都要存在
 * 2. 使用window.location.href跳转，不可后退
 * 3. 返回布尔值，便于调用方判断
 * 
 * 安全考虑：
 * 这只是前端检查，不能完全保证token有效
 * 后端API仍需验证token（在middleware/auth.js中）
 */
function checkAuth() {
  // 1. 从localStorage读取认证信息
  const token = localStorage.getItem('token');
  const username = localStorage.getItem('username');
  
  // 2. 检查是否都存在
  if (!token || !username) {
    // 2.1 任一缺失，跳转到登录页
    window.location.href = './login.html';
    return false; // 返回 false 表示认证失败
  }
  
  // 3. 显示用户名
  // 在页面顶部显示当前登录用户
  document.getElementById('userName').textContent = username;
  
  // 4. 返回true表示认证通过
  return true;
}

// ==================== UI初始化函数 ====================

/**
 * 初始化用户界面
 * 
 * @function initializeUI
 * @returns {void}
 * 
 * @description 初始化页面的各种UI组件
 * 
 * 初始化内容：
 * 1. 设置日期选择器的默认值为今天
 * 2. 渲染图标选择器（emoji图标网格）
 * 3. 渲染颜色选择器（颜色色板）
 * 4. 设置默认选中的图标和颜色
 * 
 * 设计思路：
 * 1. 使用今天作为默认日期，方便记账
 * 2. 动态生成图标和颜色选项，易于扩展
 * 3. 使用forEach遍历数组，创建DOM元素
 * 4. 使用onclick绑定事件，简洁直观
 */
function initializeUI() {
  // 1. 设置日期选择器的默认值为今天
  // toISOString()返回：2025-10-26T12:30:00.000Z
  // split('T')[0]截取日期部分：2025-10-26
  const today = new Date().toISOString().split('T')[0];
  document.getElementById('recordDate').value = today;
  
  // 2. 初始化图标选择器
  const iconPicker = document.getElementById('iconPicker');
  
  // 遍历图标数组，为每个图标创建可选择的div
  icons.forEach(icon => {
    const div = document.createElement('div');       // 创建div元素
    div.className = 'icon-option';                   // 设置CSS类名
    div.textContent = icon;                          // 显示emoji图标
    div.onclick = () => selectIcon(icon);            // 点击时选择该图标
    iconPicker.appendChild(div);                     // 添加到图标选择器中
  });
  
  // 默认选中第一个图标
  selectIcon(icons[0]);
  
  // 3. 初始化颜色选择器
  const colorPicker = document.getElementById('colorPicker');
  
  // 遍历颜色数组，为每个颜色创建可选择的div
  colors.forEach(color => {
    const div = document.createElement('div');       // 创建div元素
    div.className = 'color-option';                  // 设置CSS类名
    div.style.backgroundColor = color;               // 设置背景颜色
    div.onclick = () => selectColor(color);          // 点击时选择该颜色
    colorPicker.appendChild(div);                    // 添加到颜色选择器中
  });
  
  // 默认选中第一个颜色
  selectColor(colors[0]);
}

// 设置事件监听
function setupEventListeners() {
  // 记录类型切换
  document.getElementById('recordType').addEventListener('change', (e) => {
    updateCategoryOptions(e.target.value);
  });
  
  // 添加记录表单
  document.getElementById('recordForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    await addRecord();
  });
  
  // 创建账本表单
  document.getElementById('createBookForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    await createBook();
  });
  
  // 创新功能表单
  const quickItemForm = document.getElementById('createQuickItemForm');
  if (quickItemForm) {
    quickItemForm.addEventListener('submit', handleCreateQuickItem);
  }
  
  const budgetForm = document.getElementById('createBudgetForm');
  if (budgetForm) {
    budgetForm.addEventListener('submit', handleCreateBudget);
  }
  
  const tagForm = document.getElementById('createTagForm');
  if (tagForm) {
    tagForm.addEventListener('submit', handleCreateTag);
  }
}

// 更新分类选项
function updateCategoryOptions(type) {
  const categorySelect = document.getElementById('recordCategory');
  categorySelect.innerHTML = '<option value="">请选择分类</option>';
  
  const categories = type === 'income' ? incomeCategories : expenseCategories;
  
  Object.entries(categories).forEach(([value, label]) => {
    const option = document.createElement('option');
    option.value = value;
    option.textContent = label;
    categorySelect.appendChild(option);
  });
}

// 加载账本列表
async function loadBooks() {
  try {
    const result = await api.books.list();
    allBooks = result.data;
    
    const grid = document.getElementById('booksGrid');
    // 清空现有的账本卡片（保留添加按钮）
    grid.innerHTML = `
      <div class="book-card add-book-card" onclick="showCreateBookModal()">
        <div>+</div>
        <div style="font-size: 14px;">创建账本</div>
      </div>
    `;
    
    allBooks.forEach(book => {
      const card = createBookCard(book);
      grid.appendChild(card);
    });
    
    // 🔄 恢复上次选择的账本，或选择第一个账本
    if (allBooks.length > 0 && !currentBookId) {
      // 尝试从 localStorage 恢复上次选择的账本
      const savedBookId = localStorage.getItem('currentBookId');
      if (savedBookId && allBooks.find(b => b.book_id === parseInt(savedBookId))) {
        selectBook(parseInt(savedBookId));
      } else {
        // 如果没有保存的账本或账本不存在，选择第一个
        selectBook(allBooks[0].book_id);
      }
    }
  } catch (error) {
    alert('加载账本失败：' + error);
  }
}

// 创建账本卡片
function createBookCard(book) {
  const card = document.createElement('div');
  card.className = 'book-card';
  card.style.borderLeftColor = book.color || '#4285f4';
  if (book.book_id === currentBookId) {
    card.classList.add('active');
  }
  
  card.innerHTML = `
    <div class="book-icon">${book.icon || '💰'}</div>
    <div class="book-name">${book.book_name}</div>
    <div class="book-info">${getBookTypeLabel(book.book_type)}</div>
  `;
  
  card.onclick = () => selectBook(book.book_id);
  
  return card;
}

// 获取账本类型标签
function getBookTypeLabel(type) {
  const labels = {
    personal: '个人账本',
    family: '家庭账本',
    travel: '旅游账本',
    wedding: '婚礼账本',
    project: '项目账本'
  };
  return labels[type] || '账本';
}

// 选择账本
async function selectBook(bookId) {
  currentBookId = bookId;
  
  // 💾 保存到 localStorage，供其他页面使用
  localStorage.setItem('currentBookId', bookId);
  
  // 更新UI
  document.querySelectorAll('.book-card').forEach(card => {
    card.classList.remove('active');
  });
  
  // 高亮当前选中的账本
  const selectedCard = Array.from(document.querySelectorAll('.book-card')).find(card => {
    return card.textContent.includes(allBooks.find(b => b.book_id === bookId)?.book_name || '');
  });
  if (selectedCard) {
    selectedCard.classList.add('active');
  }
  
  // 加载该账本的数据
  await loadRecords();
  await loadStats();
  
  // 加载所有创新功能
  await loadAllInnovativeFeatures();
  
  // 📊 加载图表数据
  if (typeof initChart === 'function') {
    await initChart();
  }
  
  // 触发账本选择事件（供图表模块监听）
  window.dispatchEvent(new CustomEvent('bookSelected', { detail: { bookId } }));
  
  // 显示账本操作按钮
  document.getElementById('bookActions').style.display = 'flex';
}

// 添加记录
async function addRecord() {
  if (!currentBookId) {
    alert('请先选择一个账本');
    return;
  }
  
  const type = document.getElementById('recordType').value;
  const amount = parseFloat(document.getElementById('recordAmount').value);
  const category = document.getElementById('recordCategory').value;
  const date = document.getElementById('recordDate').value;
  const remark = document.getElementById('recordRemark').value;
  
  try {
    showLoading('正在添加记录...');
    await api.records.add({
      book_id: currentBookId,
      type,
      amount,
      category,
      date,
      remark
    });
    hideLoading();
    
    showSuccessAnimation('记录添加成功！');
    
    // 重置表单
    document.getElementById('recordForm').reset();
    document.getElementById('recordDate').value = new Date().toISOString().split('T')[0];
    
    // 刷新数据
    await loadRecords();
    await loadStats();
    
    // 📊 刷新图表
    if (typeof loadChartData === 'function') {
      await loadChartData();
    }
    
    // 🎮 更新游戏化统计（只在有游戏化UI时调用）
    if (typeof api.gamification !== 'undefined' && document.getElementById('userLevelBadge')) {
      try {
        const updateResult = await api.gamification.updateStats();
        // 检查是否升级
        if (updateResult.data.leveled_up) {
          showLevelUpAnimation(updateResult.data.leveled_up);
        }
        // 刷新等级显示
        if (typeof loadUserLevel === 'function') {
          await loadUserLevel();
        }
        // 检查新成就
        if (typeof checkAndShowNewAchievements === 'function') {
          await checkAndShowNewAchievements();
        }
      } catch (error) {
        // 静默处理游戏化错误
      }
    }
    
    // 检查成就（原有的）
    checkAchievementsQuietly();
  } catch (error) {
    hideLoading();
    showToast('添加失败：' + error, 'error');
  }
}

// 加载记录列表
async function loadRecords() {
  if (!currentBookId) return;
  
  try {
    const result = await api.records.list({ book_id: currentBookId });
    const records = result.data.records;
    
    const container = document.getElementById('recordsList');
    
    if (records.length === 0) {
      container.innerHTML = '<div class="empty-state">暂无记录，快来添加第一条吧！</div>';
      return;
    }
    
    container.innerHTML = records.map(record => `
      <div class="record-item">
        <div class="record-info">
          <div style="font-weight: bold;">${getCategoryLabel(record.category, record.type)}</div>
          <div class="record-date">${record.date} ${record.remark ? '· ' + record.remark : ''}</div>
        </div>
        <div class="record-amount ${record.type}">
          ${record.type === 'income' ? '+' : '-'}¥${record.amount}
        </div>
      </div>
    `).join('');
  } catch (error) {
    console.error('加载记录失败：', error);
  }
}

// 获取分类标签
function getCategoryLabel(category, type) {
  const categories = type === 'income' ? incomeCategories : expenseCategories;
  return categories[category] || category;
}

// 加载统计数据
async function loadStats() {
  if (!currentBookId) return;
  
  try {
    const result = await api.stats.getOverview({ book_id: currentBookId });
    const stats = result.data;
    
    document.getElementById('totalIncome').textContent = '¥' + (stats.total_income || 0);
    document.getElementById('totalExpense').textContent = '¥' + (stats.total_expense || 0);
    const balance = (stats.total_income || 0) - (stats.total_expense || 0);
    document.getElementById('totalBalance').textContent = '¥' + balance.toFixed(2);
    document.getElementById('totalBalance').style.color = balance >= 0 ? '#34a853' : '#ea4335';
    
    // 分类统计
    const categoryContainer = document.getElementById('categoryStats');
    if (stats.by_category && stats.by_category.length > 0) {
      categoryContainer.innerHTML = '<div style="margin-top: 15px; font-weight: bold; margin-bottom: 10px;">支出分类</div>' +
        stats.by_category.map(cat => `
          <div style="margin-bottom: 8px;">
            <div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
              <span>${getCategoryLabel(cat.category, 'expense')}</span>
              <span>¥${cat.amount || 0}</span>
            </div>
            <div style="background: #eee; height: 8px; border-radius: 4px; overflow: hidden;">
              <div style="background: #4285f4; height: 100%; width: ${((cat.amount || 0) / stats.total_expense * 100)}%;"></div>
            </div>
          </div>
        `).join('');
    } else {
      categoryContainer.innerHTML = '<div style="color: #999; text-align: center; margin-top: 15px;">暂无分类统计</div>';
    }
  } catch (error) {
    console.error('加载统计失败：', error);
  }
}

// 创建账本
async function createBook() {
  const name = document.getElementById('bookName').value;
  const type = document.getElementById('bookType').value;
  
  try {
    await api.books.create({
      book_name: name,
      book_type: type,
      icon: selectedIcon,
      color: selectedColor
    });
    
    alert('创建成功！');
    closeModal('createBookModal');
    document.getElementById('createBookForm').reset();
    await loadBooks();
  } catch (error) {
    alert('创建失败：' + error);
  }
}

// 图标选择
function selectIcon(icon) {
  selectedIcon = icon;
  document.querySelectorAll('.icon-option').forEach(el => {
    el.classList.toggle('selected', el.textContent === icon);
  });
}

// 颜色选择
function selectColor(color) {
  selectedColor = color;
  document.querySelectorAll('.color-option').forEach(el => {
    el.classList.toggle('selected', el.style.backgroundColor === color);
  });
}

// PIN码管理
async function setPIN() {
  const pin = document.getElementById('pinInput').value;
  
  if (!/^\d{4,6}$/.test(pin)) {
    alert('PIN码必须是4-6位数字');
    return;
  }
  
  try {
    await api.auth.setPIN(pin);
    alert('PIN码设置成功！');
    document.getElementById('pinInput').value = '';
    await checkPINStatus();
  } catch (error) {
    alert('设置失败：' + error);
  }
}

async function verifyPIN() {
  const pin = document.getElementById('pinInput').value;
  
  if (!pin) {
    alert('请输入PIN码');
    return;
  }
  
  try {
    const result = await api.auth.verifyPIN(pin);
    alert('验证成功！✓');
    document.getElementById('pinInput').value = '';
    await checkPINStatus();
  } catch (error) {
    alert('验证失败：' + error);
    await checkPINStatus();
  }
}

async function checkPINStatus() {
  try {
    const result = await api.auth.getPINStatus();
    const status = result.data;
    
    const statusDiv = document.getElementById('pinStatus');
    statusDiv.innerHTML = `
      <div style="margin-bottom: 8px;"><strong>PIN状态：</strong>${status.has_pin ? '✅ 已设置' : '❌ 未设置'}</div>
      <div style="margin-bottom: 8px;"><strong>验证状态：</strong>${status.is_verified ? '✅ 已验证' : '❌ 未验证'}</div>
      <div style="margin-bottom: 8px;"><strong>锁定状态：</strong>${status.is_locked ? '🔒 已锁定' : '🔓 正常'}</div>
      ${status.is_locked ? `<div style="color: #ea4335;">锁定至：${new Date(status.locked_until).toLocaleString()}</div>` : ''}
    `;
  } catch (error) {
    console.error('获取PIN状态失败：', error);
  }
}

// 分享账本
async function showShareModal() {
  if (!currentBookId) {
    alert('请先选择一个账本');
    return;
  }
  
  try {
    const result = await api.books.generateShareCode(currentBookId);
    const shareCode = result.data.share_code;
    
    document.getElementById('shareCodeContainer').innerHTML = `
      <div class="share-code-display">
        <div style="color: #666; margin-bottom: 10px;">分享此账本</div>
        <div class="share-code">${shareCode}</div>
        <div style="color: #999; font-size: 12px; margin-top: 10px;">
          分享码有效期：24小时<br>
          他人可通过此码加入账本
        </div>
      </div>
    `;
    
    showModal('shareModal');
  } catch (error) {
    alert('生成分享码失败：' + error);
  }
}

// 显示加入账本模态框
function showJoinModal() {
  console.log('🔔 showJoinModal 被调用');
  showModal('joinModal');
}

// 加入账本
async function joinBook() {
  const code = document.getElementById('joinCode').value.toUpperCase();
  
  if (!code || code.length !== 6) {
    alert('请输入6位分享码');
    return;
  }
  
  try {
    await api.books.join(code);
    alert('加入成功！');
    closeModal('joinModal');
    document.getElementById('joinCode').value = '';
    await loadBooks();
  } catch (error) {
    alert('加入失败：' + error);
  }
}

// 查看成员
async function showMembersModal() {
  if (!currentBookId) {
    alert('请先选择一个账本');
    return;
  }
  
  try {
    const result = await api.books.getMembers(currentBookId);
    const members = result.data;
    
    const membersList = document.getElementById('membersList');
    membersList.innerHTML = members.map(member => `
      <div style="padding: 12px; border-bottom: 1px solid #eee; display: flex; justify-content: space-between;">
        <div>
          <div style="font-weight: bold;">${member.username}</div>
          <div style="font-size: 12px; color: #666;">加入时间：${new Date(member.joined_at).toLocaleDateString()}</div>
        </div>
        <div style="color: #4285f4; font-size: 12px;">
          ${member.role === 'owner' ? '👑 所有者' : member.role === 'member' ? '👤 成员' : '👁️ 查看者'}
        </div>
      </div>
    `).join('');
    
    showModal('membersModal');
  } catch (error) {
    alert('获取成员列表失败：' + error);
  }
}

// 模态框管理
function showModal(modalId) {
  document.getElementById(modalId).classList.add('active');
}

function closeModal(modalId) {
  document.getElementById(modalId).classList.remove('active');
}

function showCreateBookModal() {
  showModal('createBookModal');
}

function showPINModal() {
  showModal('pinModal');
  checkPINStatus();
}

// 退出登录
function logout() {
  if (confirm('确定要退出登录吗？')) {
    // 清除所有登录相关数据
    localStorage.removeItem('token');
    localStorage.removeItem('username');
    localStorage.removeItem('user_info');
    localStorage.removeItem('preferredVersion');
    localStorage.removeItem('currentBookId');
    
    // 清除会话存储
    sessionStorage.clear();
    
    // 跳转到登录页
    window.location.href = './login.html';
  }
}

// ========================================
// 创新功能：快捷记账
// ========================================

async function loadQuickItems() {
  if (!currentBookId) return;
  
  try {
    const result = await api.quickItems.list({ book_id: currentBookId });
    const items = result.data;
    
    const container = document.getElementById('quickItemsList');
    
    if (items.length === 0) {
      container.innerHTML = '<div style="color: #999; text-align: center; padding: 20px; font-size: 14px;">暂无快捷项</div>';
      return;
    }
    
    container.innerHTML = items.map(item => `
      <div style="display: flex; align-items: center; justify-content: space-between; padding: 10px; margin-bottom: 8px; background: #f5f5f5; border-radius: 4px; cursor: pointer; transition: background 0.2s;" 
           onclick="useQuickItem(${item.item_id})"
           onmouseover="this.style.background='#e8f0fe'"
           onmouseout="this.style.background='#f5f5f5'">
        <div>
          <span style="font-size: 18px;">${item.icon || '💰'}</span>
          <span style="margin-left: 8px; font-weight: 500;">${item.item_name}</span>
        </div>
        <div>
          <span style="color: ${item.type === 'income' ? '#34a853' : '#ea4335'}; font-weight: bold;">¥${item.amount}</span>
          <span style="margin-left: 8px; color: #999; font-size: 12px;">${item.use_count}次</span>
        </div>
      </div>
    `).join('');
  } catch (error) {
    console.error('加载快捷项失败:', error);
  }
}

function showCreateQuickItemModal() {
  document.getElementById('createQuickItemModal').classList.add('active');
}

async function handleCreateQuickItem(e) {
  e.preventDefault();
  
  if (!currentBookId) {
    alert('请先选择一个账本');
    return;
  }
  
  const itemData = {
    book_id: currentBookId,
    item_name: document.getElementById('quickItemName').value,
    type: document.getElementById('quickItemType').value,
    amount: parseFloat(document.getElementById('quickItemAmount').value),
    category: document.getElementById('quickItemCategory').value,
    icon: document.getElementById('quickItemIcon').value || '💰'
  };
  
  try {
    await api.quickItems.create(itemData);
    alert('快捷项创建成功！');
    closeModal('createQuickItemModal');
    document.getElementById('createQuickItemForm').reset();
    await loadQuickItems();
  } catch (error) {
    alert('创建失败：' + error.message);
  }
}

async function useQuickItem(itemId) {
  if (!confirm('确认使用此快捷项记账？')) return;
  
  try {
    await api.quickItems.use(itemId, {
      book_id: currentBookId,
      date: new Date().toISOString().split('T')[0]
    });
    alert('记账成功！✓');
    await Promise.all([
      loadQuickItems(),
      loadRecords(),
      loadStats(),
      loadBudgets(),
      loadBudgetAlerts()
    ]);
  } catch (error) {
    alert('记账失败：' + error.message);
  }
}

// ========================================
// 创新功能：预算预警
// ========================================

async function loadBudgets() {
  if (!currentBookId) return;
  
  try {
    const result = await api.budgets.list({ book_id: currentBookId });
    const budgets = result.data;
    
    const container = document.getElementById('budgetsList');
    
    if (budgets.length === 0) {
      container.innerHTML = '<div style="color: #999; text-align: center; padding: 20px; font-size: 14px;">暂无预算</div>';
      return;
    }
    
    container.innerHTML = budgets.map(budget => {
      const percent = Number(budget.usage_percent) || 0;
      const level = percent >= 100 ? 'danger' : percent >= budget.alert_threshold ? 'warning' : '';
      const bgColor = level === 'danger' ? '#fef2f2' : level === 'warning' ? '#fffbec' : '#f5f5f5';
      const borderColor = level === 'danger' ? '#ea4335' : level === 'warning' ? '#fbbc04' : '#4285f4';
      
      return `
        <div style="padding: 12px; margin-bottom: 10px; border-radius: 4px; border-left: 4px solid ${borderColor}; background: ${bgColor};">
          <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
            <div style="font-weight: bold;">${budget.budget_name}</div>
            <div style="font-size: 12px; color: #666;">¥${budget.spent_amount} / ¥${budget.amount}</div>
          </div>
          <div style="height: 8px; background: #eee; border-radius: 4px; overflow: hidden; margin: 8px 0;">
            <div style="height: 100%; background: ${borderColor}; width: ${Math.min(percent, 100)}%; transition: width 0.3s;"></div>
          </div>
          <div style="font-size: 12px; color: #666;">已使用 ${percent.toFixed(1)}%</div>
        </div>
      `;
    }).join('');
  } catch (error) {
    console.error('加载预算失败:', error);
  }
}

function showCreateBudgetModal() {
  if (!currentBookId) {
    alert('请先选择一个账本');
    return;
  }
  document.getElementById('createBudgetModal').classList.add('active');
}

async function handleCreateBudget(e) {
  e.preventDefault();
  
  const budgetType = document.getElementById('budgetType').value;
  const now = new Date();
  let startDate, endDate = null;
  
  if (budgetType === 'monthly') {
    startDate = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0];
    endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0).toISOString().split('T')[0];
  } else if (budgetType === 'weekly') {
    const day = now.getDay();
    const diff = now.getDate() - day + (day === 0 ? -6 : 1);
    startDate = new Date(now.setDate(diff)).toISOString().split('T')[0];
    endDate = new Date(now.setDate(diff + 6)).toISOString().split('T')[0];
  } else {
    startDate = now.toISOString().split('T')[0];
    endDate = startDate;
  }
  
  const budgetData = {
    book_id: currentBookId,
    budget_name: document.getElementById('budgetName').value,
    budget_type: budgetType,
    amount: parseFloat(document.getElementById('budgetAmount').value),
    category: document.getElementById('budgetCategory').value || null,
    start_date: startDate,
    end_date: endDate,
    alert_threshold: parseInt(document.getElementById('budgetThreshold').value)
  };
  
  try {
    await api.budgets.create(budgetData);
    alert('预算创建成功！');
    closeModal('createBudgetModal');
    document.getElementById('createBudgetForm').reset();
    await loadBudgets();
    await loadBudgetAlerts();
  } catch (error) {
    alert('创建失败：' + error.message);
  }
}

async function loadBudgetAlerts() {
  if (!currentBookId) return;
  
  try {
    const result = await api.budgets.getAlerts({ book_id: currentBookId });
    const alerts = result.data;
    
    const container = document.getElementById('budgetAlerts');
    
    if (alerts.length === 0) {
      container.innerHTML = '<div style="color: #34a853; text-align: center; padding: 20px; font-size: 14px;">✓ 所有预算正常</div>';
      return;
    }
    
    container.innerHTML = alerts.map(alert => `
      <div style="padding: 12px; margin-bottom: 10px; border-radius: 4px; background: ${alert.alert_level === 'danger' ? '#fef2f2' : '#fffbec'}; border-left: 4px solid ${alert.alert_level === 'danger' ? '#ea4335' : '#fbbc04'};">
        <div style="font-weight: bold; margin-bottom: 4px; color: ${alert.alert_level === 'danger' ? '#ea4335' : '#fbbc04'};">
          ${alert.alert_level === 'danger' ? '⚠️ 危险' : '⚠️ 警告'}
        </div>
        <div style="font-size: 14px;">${alert.alert_message}</div>
      </div>
    `).join('');
  } catch (error) {
    console.error('加载预算预警失败:', error);
  }
}

// ========================================
// 创新功能：标签管理
// ========================================

async function loadTags() {
  try {
    const result = await api.features.getTags();
    const tags = result.data;
    
    const container = document.getElementById('tagsList');
    
    if (tags.length === 0) {
      container.innerHTML = '<div style="color: #999; font-size: 14px;">暂无标签</div>';
      return;
    }
    
    container.innerHTML = tags.map(tag => `
      <div style="padding: 4px 12px; border-radius: 16px; font-size: 12px; display: inline-flex; align-items: center; gap: 8px; background: ${tag.color}20; color: ${tag.color}; border: 1px solid ${tag.color};">
        #${tag.tag_name}
        <span style="cursor: pointer; font-weight: bold;" onclick="event.stopPropagation(); deleteTag(${tag.tag_id})">×</span>
      </div>
    `).join('');
  } catch (error) {
    console.error('加载标签失败:', error);
  }
}

function showCreateTagModal() {
  document.getElementById('createTagModal').classList.add('active');
}

async function handleCreateTag(e) {
  e.preventDefault();
  
  const tagData = {
    tag_name: document.getElementById('tagName').value,
    color: document.getElementById('tagColor').value
  };
  
  try {
    await api.features.createTag(tagData);
    alert('标签创建成功！');
    closeModal('createTagModal');
    document.getElementById('createTagForm').reset();
    await loadTags();
  } catch (error) {
    alert('创建失败：' + error.message);
  }
}

async function deleteTag(tagId) {
  if (!confirm('确认删除此标签？')) return;
  
  try {
    await api.features.deleteTag(tagId);
    await loadTags();
  } catch (error) {
    alert('删除失败：' + error.message);
  }
}

// ========================================
// 创新功能：消费趋势分析
// ========================================

async function loadTrends() {
  if (!currentBookId) return;
  
  try {
    const period = document.getElementById('trendPeriod').value;
    const result = await api.features.getTrends({ book_id: currentBookId, period });
    const data = result.data;
    
    const container = document.getElementById('trendsChart');
    
    if (data.length === 0) {
      container.innerHTML = '<div style="color: #999; text-align: center; padding: 40px; font-size: 14px;">暂无数据</div>';
      return;
    }
    
    const dateMap = {};
    data.forEach(item => {
      if (!dateMap[item.record_date]) {
        dateMap[item.record_date] = { income: 0, expense: 0 };
      }
      dateMap[item.record_date][item.type] = Number(item.daily_amount);
    });
    
    container.innerHTML = Object.entries(dateMap).map(([date, amounts]) => `
      <div style="padding: 8px 0; border-bottom: 1px solid #eee;">
        <div style="display: flex; justify-content: space-between; font-size: 12px;">
          <span>${date}</span>
          <span>
            <span style="color: #34a853;">+${amounts.income || 0}</span>
            <span style="margin: 0 8px;">|</span>
            <span style="color: #ea4335;">-${amounts.expense || 0}</span>
          </span>
        </div>
      </div>
    `).join('');
  } catch (error) {
    console.error('加载趋势数据失败:', error);
  }
}

// ========================================
// 创新功能：本月vs上月对比
// ========================================

async function loadCompare() {
  if (!currentBookId) return;
  
  try {
    const result = await api.features.getCompare({ book_id: currentBookId });
    const data = result.data;
    
    const container = document.getElementById('compareData');
    
    const currentIncome = data.current.income || 0;
    const currentExpense = data.current.expense || 0;
    const lastIncome = data.last.income || 0;
    const lastExpense = data.last.expense || 0;
    
    const incomeChange = lastIncome === 0 ? 0 : ((currentIncome - lastIncome) / lastIncome * 100).toFixed(1);
    const expenseChange = lastExpense === 0 ? 0 : ((currentExpense - lastExpense) / lastExpense * 100).toFixed(1);
    
    container.innerHTML = `
      <div style="display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid #eee;">
        <div>
          <div style="font-weight: bold; margin-bottom: 4px;">收入对比</div>
          <div style="font-size: 12px; color: #666;">本月 ¥${currentIncome} / 上月 ¥${lastIncome}</div>
        </div>
        <div style="color: ${incomeChange >= 0 ? '#34a853' : '#ea4335'}; font-weight: bold; font-size: 18px;">
          ${incomeChange >= 0 ? '↑' : '↓'} ${Math.abs(incomeChange)}%
        </div>
      </div>
      <div style="display: flex; justify-content: space-between; padding: 10px 0;">
        <div>
          <div style="font-weight: bold; margin-bottom: 4px;">支出对比</div>
          <div style="font-size: 12px; color: #666;">本月 ¥${currentExpense} / 上月 ¥${lastExpense}</div>
        </div>
        <div style="color: ${expenseChange <= 0 ? '#34a853' : '#ea4335'}; font-weight: bold; font-size: 18px;">
          ${expenseChange >= 0 ? '↑' : '↓'} ${Math.abs(expenseChange)}%
        </div>
      </div>
    `;
  } catch (error) {
    console.error('加载对比数据失败:', error);
  }
}

// ========================================
// 创新功能：账本对比
// ========================================

async function loadBooksCompare() {
  try {
    const result = await api.features.getBooksCompare();
    const books = result.data;
    
    const container = document.getElementById('booksCompare');
    
    if (books.length === 0) {
      container.innerHTML = '<div style="color: #999; text-align: center; padding: 20px; font-size: 14px;">暂无账本</div>';
      return;
    }
    
    container.innerHTML = books.map(book => `
      <div style="padding: 12px 0; border-bottom: 1px solid #eee;">
        <div style="display: flex; align-items: center; margin-bottom: 8px;">
          <span style="font-size: 20px;">${book.icon}</span>
          <span style="margin-left: 8px; font-weight: bold;">${book.book_name}</span>
        </div>
        <div style="font-size: 12px; color: #666;">
          收入 ¥${book.total_income} · 支出 ¥${book.total_expense} · ${book.record_count}条记录
        </div>
      </div>
    `).join('');
  } catch (error) {
    console.error('加载账本对比失败:', error);
  }
}

// ========================================
// 创新功能：数据导出
// ========================================

async function exportData() {
  console.log('🔍 导出功能被调用');
  console.log('🔍 当前账本ID:', currentBookId);
  
  // 如果没有选择账本，自动选择第一个
  if (!currentBookId && allBooks.length > 0) {
    currentBookId = allBooks[0].book_id;
    console.log('🔍 自动选择第一个账本:', currentBookId);
  }
  
  if (!currentBookId) {
    showToast('请先创建或选择一个账本！', 'warning');
    return;
  }
  
  showConfirm(
    '📤 导出数据',
    '确认导出当前账本的收支记录吗？',
    async () => {
  const params = { book_id: currentBookId };
  
      try {
        showLoading('正在导出数据...');
  await api.features.exportData(params);
        hideLoading();
        showSuccessAnimation('📊 导出成功！');
      } catch (error) {
        hideLoading();
        showToast('导出失败：' + error.message, 'error');
      }
    }
  );
}

// ========================================
// 创新功能：夜间模式
// ========================================

let currentTheme = 'light';

function setTheme(theme) {
  currentTheme = theme;
  if (theme === 'dark') {
    document.body.classList.add('dark-mode');
    document.getElementById('darkBtn').style.background = '#4285f4';
    document.getElementById('darkBtn').style.color = 'white';
    document.getElementById('lightBtn').style.background = '#666';
    document.getElementById('lightBtn').style.color = 'white';
  } else {
    document.body.classList.remove('dark-mode');
    document.getElementById('lightBtn').style.background = '#4285f4';
    document.getElementById('lightBtn').style.color = 'white';
    document.getElementById('darkBtn').style.background = '#666';
    document.getElementById('darkBtn').style.color = 'white';
  }
  
  // 保存设置
  api.features.updateSettings({ theme_mode: theme }).catch(err => console.error('保存主题失败:', err));
}

// 加载主题设置
async function loadTheme() {
  try {
    const result = await api.features.getSettings();
    const settings = result.data;
    if (settings.theme_mode) {
      setTheme(settings.theme_mode);
    } else {
      setTheme('light'); // 默认浅色模式
    }
  } catch (error) {
    console.error('加载主题失败:', error);
    setTheme('light'); // 出错时使用默认主题
  }
}

// 加载所有创新功能
async function loadAllInnovativeFeatures() {
  if (!currentBookId) return;
  
  await Promise.all([
    loadQuickItems(),
    loadBudgets(),
    loadTags(),
    loadTrends(),
    loadCompare(),
    loadBooksCompare(),
    loadBudgetAlerts(),
    // 新功能（游戏化功能已在 gamification-ui.js 中统一处理）
    loadGoals(),
    loadRecurringBills(),
    loadComments()
  ]);
}

// ========================================
// 🆕 新功能1：财务目标管理
// ========================================

async function loadGoals() {
  try {
    const container = document.getElementById('goalsList');
    
    // 如果页面上没有这个元素，直接返回
    if (!container) {
      return;
    }
    
    const result = await api.advanced.getGoals({ status: 'active' });
    const goals = result.data;
    
    if (goals.length === 0) {
      container.innerHTML = '<div style="color: #999; text-align: center; padding: 20px;">暂无目标</div>';
      return;
    }
    
    container.innerHTML = goals.map(goal => {
      const percent = goal.progress_percent || 0;
      const remaining = goal.target_amount - goal.current_amount;
      const color = percent >= 100 ? '#34a853' : percent >= 50 ? '#fbbc04' : '#4285f4';
      
      return `
        <div style="padding: 12px; margin-bottom: 10px; border-radius: 4px; background: #f5f5f5;">
          <div style="font-weight: bold; margin-bottom: 4px;">${goal.icon || '🎯'} ${goal.goal_name}</div>
          <div style="font-size: 12px; color: #666; margin-bottom: 8px;">
            ¥${goal.current_amount} / ¥${goal.target_amount}
          </div>
          <div style="height: 8px; background: #e0e0e0; border-radius: 4px; overflow: hidden; margin-bottom: 4px;">
            <div style="height: 100%; background: ${color}; width: ${Math.min(percent, 100)}%;"></div>
          </div>
          <div style="display: flex; justify-content: space-between; font-size: 12px; color: #666;">
            <span>${percent.toFixed(1)}%</span>
            <span>还需 ¥${remaining}</span>
          </div>
        </div>
      `;
    }).join('');
  } catch (error) {
    console.error('加载目标失败:', error);
  }
}

function showCreateGoalModal() {
  // 简化版：使用prompt
  const goalName = prompt('请输入目标名称（如：存钱买车）:');
  if (!goalName) return;
  
  const targetAmount = prompt('请输入目标金额:');
  if (!targetAmount) return;
  
  const deadline = prompt('请输入截止日期（格式：2025-12-31）:');
  if (!deadline) return;
  
  createGoal(goalName, parseFloat(targetAmount), deadline);
}

async function createGoal(goalName, targetAmount, deadline) {
  try {
    showLoading('创建目标中...');
    await api.advanced.createGoal({
      goal_name: goalName,
      goal_type: 'saving',
      target_amount: targetAmount,
      start_date: new Date().toISOString().split('T')[0],
      deadline: deadline
    });
    hideLoading();
    showSuccessAnimation('🎯 目标创建成功！');
    await loadGoals();
  } catch (error) {
    hideLoading();
    showToast('创建失败：' + error.message, 'error');
  }
}

// ========================================
// 🆕 新功能2：定期账单管理
// ========================================

async function loadRecurringBills() {
  try {
    const container = document.getElementById('recurringBillsList');
    
    // 如果页面上没有这个元素，直接返回
    if (!container) {
      return;
    }
    
    const result = await api.advanced.getRecurringBills();
    const bills = result.data;
    
    if (bills.length === 0) {
      container.innerHTML = '<div style="color: #999; text-align: center; padding: 20px;">暂无定期账单</div>';
      return;
    }
    
    container.innerHTML = bills.map(bill => `
      <div style="padding: 10px; margin-bottom: 8px; background: #f5f5f5; border-radius: 4px; display: flex; justify-content: space-between; align-items: center;">
        <div>
          <div style="font-weight: bold;">${bill.bill_name}</div>
          <div style="font-size: 12px; color: #666;">
            ${bill.recurrence_type === 'monthly' ? '每月' : '定期'} · ¥${bill.amount}
          </div>
        </div>
        <button class="btn btn-primary" style="padding: 5px 10px; font-size: 12px;" onclick="createRecordFromBill(${bill.bill_id})">记账</button>
      </div>
    `).join('');
  } catch (error) {
    console.error('加载定期账单失败:', error);
  }
}

function showCreateBillModal() {
  if (!currentBookId) {
    alert('请先选择账本');
    return;
  }
  
  const billName = prompt('账单名称（如：房租）:');
  if (!billName) return;
  
  const amount = prompt('金额:');
  if (!amount) return;
  
  createRecurringBill(billName, parseFloat(amount));
}

async function createRecurringBill(billName, amount) {
  try {
    await api.advanced.createRecurringBill({
      book_id: currentBookId,
      bill_name: billName,
      type: 'expense',
      amount: amount,
      category: 'other',
      recurrence_type: 'monthly',
      start_date: new Date().toISOString().split('T')[0]
    });
    alert('账单创建成功！');
    await loadRecurringBills();
  } catch (error) {
    alert('创建失败：' + error.message);
  }
}

async function createRecordFromBill(billId) {
  if (!confirm('确认创建记录？')) return;
  
  try {
    await api.advanced.createRecordFromBill(billId);
    alert('记账成功！');
    await Promise.all([loadRecords(), loadStats(), loadRecurringBills()]);
  } catch (error) {
    alert('记账失败：' + error.message);
  }
}

// ========================================
// 🆕 新功能3：成就系统（已迁移到 gamification-ui.js）
// ========================================
// 游戏化功能现在统一在 gamification-ui.js 中处理
// 这里的代码已废弃，保留仅用于参考

// ========================================
// 🆕 新功能4：留言板
// ========================================

// 显示留言板模态框
function showCommentsModal() {
  if (!currentBookId) {
    showToast('请先选择账本', 'warning');
    return;
  }
  
  showModal('commentsModal');
  loadCommentsContent();
}

// 加载留言内容
async function loadCommentsContent() {
  if (!currentBookId) return;
  
  try {
    const container = document.getElementById('commentsList');
    
    if (!container) {
      console.error('commentsList容器不存在');
      return;
    }
    
    container.innerHTML = '<div style="text-align: center; padding: 20px; color: #999;">加载中...</div>';
    
    const result = await api.advanced.getComments(currentBookId);
    const comments = result.data;
    
    if (comments.length === 0) {
      container.innerHTML = '<div style="color: #999; text-align: center; padding: 40px;">📝 暂无留言<br><br>点击上方按钮添加第一条留言吧！</div>';
      return;
    }
    
    container.innerHTML = comments.map(comment => `
      <div style="padding: 15px; margin-bottom: 10px; background: linear-gradient(135deg, #667eea22 0%, #764ba222 100%); border-radius: 8px; border-left: 3px solid #667eea;">
        <div style="font-weight: bold; font-size: 13px; color: #333; margin-bottom: 6px;">
          👤 ${comment.nickname || comment.username}
        </div>
        <div style="font-size: 14px; color: #555; margin-bottom: 8px; line-height: 1.5;">
          ${comment.content}
        </div>
        <div style="font-size: 11px; color: #999;">
          ⏰ ${new Date(comment.created_at).toLocaleString()}
        </div>
      </div>
    `).join('');
  } catch (error) {
    console.error('加载留言失败:', error);
    const container = document.getElementById('commentsList');
    if (container) {
      container.innerHTML = '<div style="color: #ea4335; text-align: center; padding: 20px;">❌ 加载失败：' + error.message + '</div>';
    }
  }
}

// 显示添加留言对话框
function showAddCommentDialog() {
  if (!currentBookId) {
    showToast('请先选择账本', 'warning');
    return;
  }
  
  const content = prompt('请输入留言内容：');
  if (!content || content.trim() === '') {
    return;
  }
  
  addComment(content.trim());
}

// 添加留言
async function addComment(content) {
  try {
    await api.advanced.addComment({
      book_id: currentBookId,
      content: content
    });
    showToast('💬 留言成功！', 'success');
    await loadCommentsContent(); // 刷新留言列表
  } catch (error) {
    showToast('留言失败：' + error.message, 'error');
  }
}

// 兼容旧的函数名
async function loadComments() {
  await loadCommentsContent();
}

function showAddCommentModal() {
  showAddCommentDialog();
}

// ========================================
// 🆕 新功能5：分析报告
// ========================================

// 显示分析报告模态框
function showAnalysisReportModal() {
  if (!currentBookId) {
    showToast('请先选择账本', 'warning');
    return;
  }
  
  showModal('analysisReportModal');
  generateAnalysisReportContent();
}

// 生成分析报告内容
async function generateAnalysisReportContent() {
  if (!currentBookId) {
    showToast('请先选择账本', 'warning');
    return;
  }
  
  try {
    const container = document.getElementById('analysisReport');
    
    if (!container) {
      console.error('analysisReport容器不存在');
      return;
    }
    
    container.innerHTML = '<div style="text-align: center; padding: 40px; color: #999;">⏳ 正在分析数据...</div>';
    
    const result = await api.advanced.generateReport(currentBookId, 'monthly');
    const data = result.data;
    
    container.innerHTML = `
      <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 20px; border-radius: 12px; color: white; box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);">
        <div style="font-weight: bold; font-size: 18px; margin-bottom: 15px; text-align: center;">
          📊 本月财务报告
        </div>
        
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
          <div style="background: rgba(255,255,255,0.2); padding: 15px; border-radius: 8px; text-align: center;">
            <div style="font-size: 12px; opacity: 0.9; margin-bottom: 5px;">💰 总收入</div>
            <div style="font-size: 24px; font-weight: bold;">¥${data.total_income || 0}</div>
          </div>
          <div style="background: rgba(255,255,255,0.2); padding: 15px; border-radius: 8px; text-align: center;">
            <div style="font-size: 12px; opacity: 0.9; margin-bottom: 5px;">💸 总支出</div>
            <div style="font-size: 24px; font-weight: bold;">¥${data.total_expense || 0}</div>
          </div>
        </div>
        
        <div style="background: rgba(255,255,255,0.2); padding: 15px; border-radius: 8px; margin-bottom: 15px;">
          <div style="display: flex; justify-content: space-around; text-align: center;">
            <div>
              <div style="font-size: 12px; opacity: 0.9; margin-bottom: 5px;">📝 记录数</div>
              <div style="font-size: 20px; font-weight: bold;">${data.record_count || 0} 条</div>
            </div>
            <div>
              <div style="font-size: 12px; opacity: 0.9; margin-bottom: 5px;">📅 日均支出</div>
              <div style="font-size: 20px; font-weight: bold;">¥${data.avg_daily_expense || 0}</div>
            </div>
            <div>
              <div style="font-size: 12px; opacity: 0.9; margin-bottom: 5px;">💵 净收益</div>
              <div style="font-size: 20px; font-weight: bold;">¥${((data.total_income || 0) - (data.total_expense || 0)).toFixed(2)}</div>
            </div>
          </div>
        </div>
        
        ${data.insights && data.insights.length > 0 ? `
          <div style="background: rgba(255,255,255,0.15); padding: 15px; border-radius: 8px;">
            <div style="font-weight: bold; font-size: 14px; margin-bottom: 10px;">💡 智能分析建议</div>
            ${data.insights.map(insight => `
              <div style="font-size: 13px; margin: 8px 0; padding-left: 15px; position: relative; line-height: 1.6;">
                <span style="position: absolute; left: 0;">▪</span>
                ${insight}
              </div>
            `).join('')}
          </div>
        ` : `
          <div style="background: rgba(255,255,255,0.15); padding: 15px; border-radius: 8px; text-align: center; font-size: 13px; opacity: 0.9;">
            💡 暂无分析建议，继续记账以获得更多数据分析
          </div>
        `}
      </div>
    `;
    
    showToast('📊 报告生成成功！', 'success');
  } catch (error) {
    console.error('生成分析报告失败:', error);
    const container = document.getElementById('analysisReport');
    if (container) {
      container.innerHTML = `
        <div style="text-align: center; padding: 40px; color: #ea4335;">
          <div style="font-size: 48px; margin-bottom: 10px;">❌</div>
          <div style="font-size: 16px; margin-bottom: 10px;">生成失败</div>
          <div style="font-size: 14px; opacity: 0.8;">${error.message}</div>
        </div>
      `;
    }
    showToast('生成失败：' + error.message, 'error');
  }
}

// 兼容旧的函数名
async function generateAnalysisReport() {
  showAnalysisReportModal();
}

// ========================================
// 🆕 新功能6：数据备份
// ========================================

async function backupData() {
  showConfirm(
    '📦 数据备份',
    '确认备份所有账本和记录数据吗？',
    async () => {
      try {
        showLoading('正在备份数据...');
        await api.advanced.createBackup();
        hideLoading();
        showSuccessAnimation('💾 备份成功！');
        setTimeout(() => showToast('备份文件已下载到您的电脑', 'success'), 2500);
      } catch (error) {
        hideLoading();
        showToast('备份失败：' + error.message, 'error');
      }
    }
  );
}

// ========================================
// 🆕 新功能7：排行榜（已迁移到 gamification-ui.js）
// ========================================
// 游戏化功能现在统一在 gamification-ui.js 中处理
// 这里的代码已废弃，保留仅用于参考 